package com.risen.project.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class CommonController {

    @PostMapping("/ESBWeb/servlets/33.1111.zjhz.SInmROtCOh.SynReq@1.0")
    public JSONObject synReq(HttpServletRequest request, String idNum, String AppKey) {
        // 请求头
        String appKey = request.getHeader("appKey");
        String appSecret = request.getHeader("appSecret");
        System.out.println(appKey + "__" + appSecret);

        String idNum1 = request.getParameter("idNum");
        String AppKey1 = request.getParameter("AppKey");
        System.out.println("idNum=[" + idNum1 + "] AppKey=[" + AppKey1 + "]");

        JSONObject res = new JSONObject();
        res.put("code", 200);
        res.put("msg", "成功");
        JSONObject data = new JSONObject();
        data.put("colorCode", "GREEN");
        data.put("userName", "测试");
        data.put("idNum", idNum);

        List<String> pnList = new ArrayList<>();
        pnList.add("aCvW7MNNpyEYSjCJgMsNKQ==");
        pnList.add("kNQasacUGB4IW32PpvbW3Q==");


        data.put("pn", pnList.get((int) (Math.random() * 2)));
        res.put("data", data);

        return res;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TimeInterval timer = DateUtil.timer();

        //1.第一步
        check1();
        //2.第二步
        check2();
        //3.第三步
        check3();

        System.out.println("同步花费毫秒数：" + timer.interval());
        timer.restart();

        CompletableFuture<Void> check1 = CompletableFuture.runAsync(CommonController::check1);
        CompletableFuture<Void> check2 = CompletableFuture.runAsync(CommonController::check2);
        CompletableFuture<Void> check3 = CompletableFuture.runAsync(CommonController::check3);
        CompletableFuture.allOf(check1, check2, check3);
        check1.get();
        check2.get();;
        check3.get();

        System.out.println("异步花费毫秒数：" + timer.interval());
    }

    public static void check1() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void check2() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void check3() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
